package com.itheima.filter;


import com.aliyuncs.utils.StringUtils;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")
//先统一拦截全部请求
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取访问请求
        String requestURI = request.getRequestURI();
//        System.out.println(requestURI);
        //检测是否是login请求，如果是的话就放行
        if(requestURI.contains("login")){
            filterChain.doFilter(servletRequest,servletResponse);
//            总结来说，return; 语句在 chain.doFilter 之后的作用是确保在满足特定条件时，过滤器方法能够立即返回，避免不必要的代码执行，提高代码的效率和可读性。
            return;
        }

        //如果不是login请求的话，先拿出token来哦
        String token = request.getHeader("token");
        log.info("token:{}",token);

        if(token==null){
            //如果token为空的话 直接返回就可以了
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

            //如果不为空的话
        try{
            //解析token
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            //如果有异常的话 说明解析的不对 那就直接返回就可以 了
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
